package com.ruoyi.duanju.service.my;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.duanju.domain.DjInputFile;
import com.ruoyi.duanju.domain.DjInputFileDetail;
import com.ruoyi.duanju.service.IDjInputFileDetailService;
import com.ruoyi.duanju.service.IDjInputFileService;
import com.ruoyi.duanju.service.impl.DjInputFileServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class MyDjService {

    @Autowired
    IDjInputFileService iDjInputFileService;
    @Autowired
    IDjInputFileDetailService iDjInputFileDetailService;

    @Transactional(rollbackFor = Exception.class)
    public int inputFile(DjInputFile djInputFile) throws IOException {
        File file = FileUtils.getFile(djInputFile.getFile().replace("/profile", RuoYiConfig.getProfile()));
        iDjInputFileService.insertDjInputFile(djInputFile);
        covertTo(djInputFile,file);
//        for(DjInputFileDetail temp : detailList){
//            iDjInputFileDetailService.insertDjInputFileDetail(temp);
//        }

        return 1;
    }

    private List<DjInputFileDetail> covertTo(DjInputFile inputFile,File file) throws IOException {
        ExcelUtil<DjInputFileDetail> excelUtil = new ExcelUtil<>(DjInputFileDetail.class);
        List<DjInputFileDetail> list = excelUtil.importExcel(new FileInputStream(file));
        //获取token

        for(DjInputFileDetail temp : list){
            temp.setCreateTime(new Date());
            temp.setArticleInputFileId(inputFile.getId());
            temp.setInputStatus(1);

            //上传图片
            String arrStr = temp.getImgList();
            if(StringUtils.isNotEmpty(arrStr) && !"[]".equals(arrStr)){
                List<String> arr = JSON.parseArray(arrStr,String.class);
                File[] tempFiles = new File[arr.size()];
                for(int i=0;i<arr.size();i++){
                    tempFiles[i] = new File(arr.get(i));
                }
                String uploadRes = uploads(tempFiles);
                List<String> uploadResList = JSON.parseArray(uploadRes,String.class);
                if(CollectionUtils.isNotEmpty(uploadResList)){
                    temp.setAvatar(uploadResList.get(0));
                }
                temp.setUrlList(uploadRes);
                temp.setContent(covertContent(temp.getAiContent(), uploadResList,temp.getShareUrl(),temp.getShareCode()));
                iDjInputFileDetailService.insertDjInputFileDetail(temp);
            }

        }
        return list;
    }

    private String covertContent(String aiContent,List<String> imgList,String shareUrl, String shareCode){
        StringBuffer sb = new StringBuffer();
        aiContent = "<p>" + aiContent.replaceAll("\n\n", "</p><br/><p>") + "</p><br/>";
        sb.append(aiContent);

        if(CollectionUtils.isNotEmpty(imgList)) {
            sb.append("<p><br></p><p>");
            for(String img : imgList) {
                sb.append("<img src=\"").append(img).append("\">");
            }
            sb.append("</p><p><br/></p>");
        }

//        sb.append("<p style=\"color:red;font-size:20px\" >网盘链接，转存后观看：").append(shareUrl).append("</p>");
//        sb.append("<br>");
//        sb.append("<p style=\"color:red;font-size:20px\" >提取码：<br/>");
//        if(StringUtils.isEmpty(shareCode)){
//            sb.append("无需提取码");
//        }else{
//            sb.append(shareCode);
//        }
//        sb.append("</p><p><br/></p><p><br/></p><p><br/></p>");
        sb.append("<p><br/></p><p><br/></p>");
        return sb.toString();
    }

    private static MultipartFile getMultipartFileByPath(String filePath) throws IOException {
        File file = new File(filePath);
        try (FileInputStream input = new FileInputStream(file)) {
            return new MockMultipartFile(
                    "file",                  // 表单字段名
                    file.getName(),          // 原始文件名
                    null,
                    input
            );
        }
    }

    private static String upload(File file){
        HttpResponse response = HttpRequest.post("http://admin.fyliu.cn/prod-api/common/upload").form("file",file).execute();
        System.out.println(response.body());
        AjaxResult result = JSON.parseObject(response.body(),AjaxResult.class);
        if(result.isSuccess()){
            return (String) result.get("url");
        }else{
            return "";
        }
    }

    private static String uploads(File[] files){
        HttpResponse response = HttpRequest.post("http://admin.fyliu.cn/prod-api/common/uploads").form("files",files).execute();
        AjaxResult ajaxResult = JSON.parseObject(response.body(),AjaxResult.class);
        if(ajaxResult.isSuccess()){
            return JSON.toJSONString(((String) ajaxResult.get("urls")).split(","));
        }
        return "[]";
    }

    public static void main(String[] args) throws IOException {
//        ['D:\\文档\\个人\\分享数据\\图片\\口袋妖怪：传说绿宝石 终极版 v1.5.4.8.5 PC+手机0.jpg', 'D:\\文档\\个人\\分享数据\\图片\\口袋妖怪：传说绿宝石 终极版 v1.5.4.8.5 PC+手机1.jpg', 'D:\\文档\\个人\\分享数据\\图片\\口袋妖怪：传说绿宝石 终极版 v1.5.4.8.5 PC+手机2.jpg']
//        String url = upload(new File("D:\\\\文档\\\\个人\\\\分享数据\\\\图片\\\\口袋妖怪：传说绿宝石 终极版 v1.5.4.8.5 PC+手机0.jpg"));
//        System.out.println(url);
        List<String> arrStrs = JSON.parseArray("['D:\\\\文档\\\\个人\\\\分享数据\\\\图片\\\\口袋妖怪：传说绿宝石 终极版 v1.5.4.8.5 PC+手机0.jpg', 'D:\\\\文档\\\\个人\\\\分享数据\\\\图片\\\\口袋妖怪：传说绿宝石 终极版 v1.5.4.8.5 PC+手机1.jpg', 'D:\\\\文档\\\\个人\\\\分享数据\\\\图片\\\\口袋妖怪：传说绿宝石 终极版 v1.5.4.8.5 PC+手机2.jpg']",String.class);
        File[] files = new File[arrStrs.size()];

        for (int i=0;i<arrStrs.size();i++){
            File tempFile = new File(arrStrs.get(i));
            files[i] = tempFile;
        }
        String url = uploads(files);
        System.out.println(url);
    }


}
